package com.jlect.swebing.ui.client.menu;

import com.jlect.swebing.renderers.client.Image;
import com.jlect.swebing.renderers.client.RendererActionListener;
import com.jlect.swebing.renderers.client.RendererEvent;
import com.jlect.swebing.ui.client.*;
import com.jlect.swebing.ui.client.button.*;

/**
 * Menu item component. It appears at the {@link com.jlect.swebing.ui.client.menu.GMenu}
 * component and could listen to the user clicks
 *
 * @author Sergey Kozmin
 * @since 23.11.2007 10:05:15
 */
public class GMenuItem extends GContainer implements RendererActionListener {
    private ActionListenerCollection listeners;
    private MouseEventsRedirector redirector = new MouseEventsRedirector(this);
    private String text;

    public GMenuItem(String text, Image image) {
        this.text = text;
        setLayoutManager(new FlowLayout());
        GLabel label = new GLabel(text);
        addComponent(label);

        //redirect mouse events to toggle button listeners
        label.addMouseListener(redirector);

        ButtonView view = new ToggleButtonViewImpl(this);
        ToggleButtonRendererAdapter toggleButtonRendererAdapter = new ToggleButtonRendererAdapter(label);
        toggleButtonRendererAdapter.setActionListener(this);
        view.setButtonComponent(toggleButtonRendererAdapter);
        ButtonModel model = new DefaultButtonModelImpl(this);
        ButtonBase base = new ButtonBase(model, view,
                new ToggleButtonControllerImpl());

        model.setButtonText(text);
        model.setButtonImage(image);

        setPreferredSize(new Dimension(120, 50));//todo change with font metrix call
    }

    public GMenuItem(String text) {
        this(text, null);
    }

    public void addActionListener(ActionListener listener) {
        getActionListeners().add(listener);
    }

    public void removeActionListener(ActionListener listener) {
        if(listeners != null) {
            getActionListeners().remove(listener);
        }
    }

    protected ActionListenerCollection getActionListeners() {
        if(listeners == null) {
            listeners = new ActionListenerCollection();
        }
        return listeners;
    }

    public void fireActionPerformed(RendererEvent event) {
        //todo make it be calling from somewhere
        getActionListeners().clickActionPerformed(this);
    }

    public String getText() {
        return text; 
    }
}
